<template>
  <div class="categories">
    <el-card>
      <template #header>
        <div class="header-bar">
          <div class="left-section">
            <span class="title">分类管理</span>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索分类名称"
              clearable
              style="width: 250px; margin-left: 20px"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button @click="handleSearch">搜索</el-button>
          </div>
          <div class="right-section">
            <el-button type="primary" :icon="Plus" @click="handleAdd">
              添加分类
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="filteredCategoryList" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="分类名称" min-width="150">
          <template #default="{ row }">
            <div class="category-name">
              <span v-if="row.icon" class="category-icon">{{ row.icon }}</span>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productCount" label="商品数量" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.productCount > 0 ? 'success' : 'info'" size="large">
              <el-icon style="margin-right: 4px;"><ShoppingBag /></el-icon>
              {{ row.productCount || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" sortable align="center">
          <template #default="{ row }">
            <el-tag type="info">{{ row.sort }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button 
              :type="row.status === 1 ? 'warning' : 'success'" 
              size="small"
              text 
              @click="handleToggleStatus(row)"
            >
              <el-icon><Switch /></el-icon>
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" text @click="handleDelete(row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="categoryList.length === 0 && !loading" class="empty-data">
        <el-empty description="暂无分类数据" />
      </div>
    </el-card>
    
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select 
            v-model="form.icon" 
            placeholder="请选择图标（可选）" 
            clearable
            style="width: 100%"
          >
            <el-option label="🍔 食品" value="🍔" />
            <el-option label="🥤 饮料" value="🥤" />
            <el-option label="🍭 零食" value="🍭" />
            <el-option label="🍞 烘焙" value="🍞" />
            <el-option label="🍜 速食" value="🍜" />
            <el-option label="🍱 便当" value="🍱" />
            <el-option label="🥗 生鲜" value="🥗" />
            <el-option label="🍦 冷饮" value="🍦" />
            <el-option label="☕ 咖啡茶饮" value="☕" />
            <el-option label="🧃 果汁" value="🧃" />
            <el-option label="🧹 日用品" value="🧹" />
            <el-option label="🧴 洗护用品" value="🧴" />
            <el-option label="📚 文具" value="📚" />
            <el-option label="🎮 玩具" value="🎮" />
            <el-option label="💊 保健品" value="💊" />
            <el-option label="🌸 化妆品" value="🌸" />
            <el-option label="🧦 服饰" value="🧦" />
            <el-option label="⚡ 电子产品" value="⚡" />
            <el-option label="🏠 家居用品" value="🏠" />
            <el-option label="📦 其他" value="📦" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Edit, Delete, Switch, ShoppingBag } from '@element-plus/icons-vue'
import { getCategoryList, addCategory, updateCategory, deleteCategory } from '@/api/category'

const loading = ref(false)
const dialogVisible = ref(false)
const formRef = ref(null)
const submitting = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')

const categoryList = ref([])

// 筛选后的分类列表
const filteredCategoryList = computed(() => {
  if (!searchKeyword.value) {
    return categoryList.value
  }
  return categoryList.value.filter(item => 
    item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const form = reactive({
  id: null,
  name: '',
  icon: null,
  sort: 0,
  status: 1,
  parentId: 0
})

const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

const dialogTitle = computed(() => isEdit.value ? '编辑分类' : '添加分类')

onMounted(() => {
  loadCategories()
})

// 加载分类列表
const loadCategories = async () => {
  loading.value = true
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      categoryList.value = res.data
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载分类列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(form, {
    id: row.id,
    name: row.name,
    icon: row.icon || null,
    sort: row.sort || 0,
    status: row.status,
    parentId: row.parentId || 0
  })
  dialogVisible.value = true
}

// 启用/禁用分类
const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(`确定要${action}该分类吗？`, '提示', {
      type: 'warning'
    })
    
    // 包含所有必需字段
    const submitData = {
      id: row.id,
      name: row.name,  // 必需字段
      parentId: row.parentId || 0,
      sort: row.sort || 0,
      icon: row.icon || null,
      status: row.status === 1 ? 0 : 1
    }
    
    const res = await updateCategory(submitData)
    if (res.code === 200) {
      ElMessage.success(`${action}成功`)
      loadCategories()
    } else {
      ElMessage.error(res.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}失败:`, error)
      ElMessage.error(error.response?.data?.message || error.message || `${action}失败`)
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该分类吗？删除后不可恢复，且该分类下不能有商品。',
      '提示',
      {
        type: 'warning'
      }
    )
    
    const res = await deleteCategory(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadCategories()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || error.message || '删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const submitData = {
          name: form.name,
          icon: form.icon || null,
          sort: form.sort || 0,
          status: form.status,
          parentId: form.parentId || 0
        }
        
        if (isEdit.value) {
          submitData.id = form.id
          const res = await updateCategory(submitData)
          if (res.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            loadCategories()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          const res = await addCategory(submitData)
          if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            loadCategories()
          } else {
            ElMessage.error(res.message || '添加失败')
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(error.response?.data?.message || error.message || '操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.id = null
  form.name = ''
  form.icon = null
  form.sort = 0
  form.status = 1
  form.parentId = 0
}

// 搜索功能
const handleSearch = () => {
  // 筛选逻辑在 computed 中处理
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style lang="scss" scoped>
.categories {
  .header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .left-section {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .title {
        font-size: 18px;
        font-weight: bold;
      }
    }
    
    .right-section {
      display: flex;
      gap: 10px;
    }
  }
  
  .category-name {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .category-icon {
      font-size: 20px;
      line-height: 1;
    }
  }
  
  .empty-data {
    padding: 40px 0;
  }
  
  :deep(.el-badge) {
    .el-badge__content {
      background-color: #409eff;
    }
  }
}
</style>












